package com.littlerpc.protocol.net.netty.codec;

import com.littlerpc.protocol.codec.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 *
 * @author ChengPeng
 * @date 2017/6/14
 */
public class NettyDecoder extends ByteToMessageDecoder{

    private Serializer serializer;
    private Class<?> genericClass;


    public NettyDecoder(Serializer serializer, Class<?> genericClass) {
        this.serializer = serializer;
        this.genericClass = genericClass;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf
            in, List<Object> out) throws Exception {
        if(in.readableBytes() < 4){
            return;
        }
//        in.markReaderIndex();
        int length  = in.readInt();
        byte [] data = new byte[length];
        in.readBytes(data);
        Object obj = serializer.deserialize(data, genericClass);
        out.add(obj);
    }
}
